<template>
  <div class="login">
    <el-form ref="loginRef" :model="loginForm" :rules="loginRules" class="login-form" label-suffix="：">
      <h3 class="title">{{ title }}</h3>
      <el-form-item prop="username" label="账号">
        <el-autocomplete v-model="loginForm.username"
                         :fetch-suggestions="queryUsernames"
                         :trigger-on-focus="true"
                         clearable
                         value-key="value"
                         debounce="100"
                         placeholder="账号" style="width: 100%;padding: 0;">
        </el-autocomplete>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="loginForm.password"
                  type="password"
                  auto-complete="off"
                  placeholder="密码"
                  @keyup.enter="handleLogin" style="height: 32px;">
          <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
        </el-input>
      </el-form-item>
      <el-form-item prop="code" v-if="captchaType === 'image' || captchaType === 'static'">
        <el-input v-model="loginForm.code"
                  auto-complete="off"
                  placeholder="验证码"
                  style="width: 63%"
                  @keyup.enter="handleLogin">
          <template #prefix><svg-icon icon-class="validCode" class="el-input__icon input-icon" /></template>
        </el-input>
        <div class="login-code">
          <img alt="" :src="codeUrl" @click="getCode" class="login-code-img"/>
        </div>
      </el-form-item>
      <Verify @success="captchaCheckSuccess"
              :mode="'pop'"
              :captchaType="captchaType"
              :imgSize="{ width: '330px', height: '155px' }"
              ref="verify"
              v-if="captchaType === 'blockPuzzle' || captchaType === 'clickWord'" />
      <el-checkbox v-model="loginForm.rememberMe" style="margin:0 0 25px 0;">记住密码</el-checkbox>
      <el-form-item style="width:100%;">
        <el-button :loading="loading"
                   type="primary"
                   style="width:100%;"
                   @click.prevent="handleLogin">
          <span v-if="!loading">登 录</span>
          <span v-else>登 录 中...</span>
        </el-button>
        <div style="float: right;" v-if="register">
          <router-link class="link-type" :to="'/register'">立即注册</router-link>
        </div>
      </el-form-item>
    </el-form>
    <!--  底部  -->
    <div class="el-login-footer">
      <span>Copyright © 2023 caizhh All Rights Reserved.</span>
    </div>
  </div>
</template>

<script setup>
import Cookies from "js-cookie";
import {encrypt, decrypt} from "@/utils/jsencrypt";
import useUserStore from '@/store/modules/user'
import {getCurrentInstance, ref} from "vue";
import {useRouter} from "vue-router";
import settings from "@/settings";
import initListStore from '@/store/modules/initList'
import {
  alertError, alertErrorMsg,
  alertInfo,
  alertInfoMsg,
  alertSuccess,
  alertSuccessMsg, alertWarning, alertWarningMsg,
  isDebugMode, isNullOrUndefined, notifyError,
  notifyInfo,
  notifySuccess, notifyWarning,
  svc
} from "@/config/common";
import {doGet} from "@/config/http";
import Verify from "@/components/Verifition/Verify";

const router = useRouter();
const {proxy} = getCurrentInstance();
const title = settings.title

const loginForm = ref({
  username: isDebugMode() ? 'admin' : "",
  password: isDebugMode() ? 'admin123' : "",
  rememberMe: false,
  code: "",
  uuid: "",
});

const loginRules = {
  username: [{ required: true, trigger: "blur", message: "请输入您的账号" }],
  password: [{ required: true, trigger: "blur", message: "请输入您的密码" }],
  code: [{ required: true, trigger: "change", message: "请输入验证码" }],
};

const codeUrl = ref("");
const loading = ref(false);
// 验证码开关
const captchaType = ref('') // static 为静态图、image 为图形、blockPuzzle 为滑块、clickWord 为文字点选
// 注册开关
const register = ref(false);
const redirect = ref(undefined);

function captchaCheckSuccess(params) {
  loginForm.value.code = params.captchaVerification;
  loading.value = true;
  if (loginForm.value.rememberMe) {
    Cookies.set("username", loginForm.value.username, { expires: 30 });
    Cookies.set("password", encrypt(loginForm.value.password), { expires: 30, });
    Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
  } else {
    Cookies.remove("username");
    Cookies.remove("password");
    Cookies.remove("rememberMe");
  }
  proxy.$store.dispatch("Login", loginForm.value).then(() => {
    sessionStorage.setItem('isPublicList', '1')
    proxy.$router.push({ path: "/" })
    initListStore().publicList()
    initListStore().baseList()
    initListStore().budgetList()
    initListStore().expenditureList()
    initListStore().contractList()
  }).catch(() => {
    loading.value = false;
  });
}

function info() {
  alertInfoMsg("alertInfoMsg")
  alertInfo("alertInfo")
  notifyInfo("notifyInfo")
}
function success() {
  alertSuccessMsg("alertSuccessMsg")
  alertSuccess("alertSuccess")
  notifySuccess("notifySuccess")
}
function warning() {
  alertWarningMsg("alertWarningMsg")
  alertWarning("alertWarning")
  notifyWarning("notifyWarning")
}
function error() {
  alertErrorMsg("alertErrorMsg")
  alertError("alertError")
  notifyError("notifyError")
}

async function handleLogin() {
  const formName = 'loginRef'
  let v = await proxy.$refs[formName].validate().catch((err)=>{return err})
  if (v !== true) {
    return
  }
  if (captchaType.value === 'blockPuzzle' || captchaType.value === 'clickWord') {
    proxy.$refs.verify.show()
  } else {

    doLogin()

    console.log('执行登录操作。。。。。。')
  }
}

function doLogin() {
  loading.value = true;
  // 调用action的登录方法
  useUserStore().login(loginForm.value).then(() => {
    // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
    if (loginForm.value.rememberMe) {
      Cookies.set("username", loginForm.value.username, { expires: 30 });
      Cookies.set("password", encrypt(loginForm.value.password), { expires: 30 });
      Cookies.set("rememberMe", loginForm.value.rememberMe, { expires: 30 });
    } else {
      // 否则移除
      Cookies.remove("username");
      Cookies.remove("password");
      Cookies.remove("rememberMe");
    }
    let usernames = localStorage.getItem('usernames');
    if (isNullOrUndefined(usernames)) {
      usernames = ''
    }
    if (usernames.indexOf(loginForm.value.username) === -1) {
      usernames = usernames + ',' + loginForm.value.username
    }
    let names = typeof usernames === 'string' ? usernames : usernames.join(',')
    localStorage.setItem('usernames', names)
    initListStore().publicList().then(() => {
      sessionStorage.setItem('isPublicList', '1')
      router.push({ path: redirect.value || "/" });
    })
    
    
  }).catch(() => {
    loading.value = false;
    // 重新获取验证码
    if (captchaType.value === 'image' || captchaType.value === 'static') {
      getCode();
    }
  })
}

async function getCode() {
  if (captchaType.value === 'image') {
    let res = await doGet(svc, '/customCaptcha/captchaImage', {type: 'math'}, false)
    if (res) {
      codeUrl.value = "data:image/gif;base64," + res.img
      loginForm.value.uuid = res.uuid
    }
  }
  if (captchaType.value === 'static') {
    let res = {
      "msg": "操作成功",
      "img": "/9j/4AAQSkZJRgABAgAAAQABAAD/2wBD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o+61sCmPrjP610WteFYtauYtShn+z+fErSRiPdk469R2wPwrqdK8KXEG3INdha+HVZBvWuWrnUueNXC01Skrq8UtU7bqxSp6Wk7nklp4M0+JcSW8lwe7O5H8sUk/gC0ncNaXE1q3XDDeB9OQR+de3ReHoFH3BQfD0IbIUVhDOcfCfOq0r+buvuen4D9nDseNeKbPUbTSIZLeeZrtWRWeFSGk4wTxyOea7X4Qajqr6Vc2mrLdb4pcxPchtzKw6ZPXBB/Oui1Dw95i4Vat6HpL2ZGaz+vf7I8M4LV3v19B8vvXudUnIqtq//ACBL/wD69pP/AEE1ZjGFFV9X/wCQJf8A/XtJ/wCgmvOl8LCXws5Ky/48rf8A65r/ACqyK5mLWrmKJI1SIhFCjIPb8ak/t+6/55w/98n/ABrKNaNkZxqxsjpRThXM/wDCQ3f/ADzg/wC+T/jS/wDCRXf/ADzg/wC+T/jVe2iP20TqNuaaYEbqormv+EkvP+eUH/fJ/wAaX/hJbz/nlB/3yf8AGj20Q9tE6RLSNTkKKsqoUcVyf/CT3v8Azyt/++W/xpf+Eovf+eVv/wB8t/jR7aIe2idaYww5FKkKqeBXJf8ACVX3/PK3/wC+W/xpf+Ervv8Anlbf98t/jR7aIe2idc8CyDBGajXT4Qc7BXLf8Jbf/wDPG2/75b/Gl/4S/UP+eNt/3y3/AMVR7aIe2idgltGvRRVhUA6CuI/4TDUP+eNr/wB8t/8AFUv/AAmWo/8APG1/75b/AOKo9tEPbRO6ApwFcJ/wmeo/88bX/vhv/iqX/hNdS/54Wn/fDf8AxVHtoh7aJ3flg9RT0jC9BXBf8JtqX/PC0/74b/4ql/4TjU/+eFp/3w3/AMVR7aIe2ieggVV1f/kB6h/17Sf+gmuK/wCE51P/AJ4Wn/fDf/FVHc+M9RurWa3eG1CSoyMVVsgEY4+aplWjZilVjZn/2Q==",
      "code": 200,
      "uuid": "c5d7bdfcf0a342859329d9869f2768c0"
    }
    codeUrl.value = "data:image/gif;base64," + res.img
    loginForm.value.uuid = res.uuid
  }
}

function getCookie() {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");
  loginForm.value.username = isNullOrUndefined(username) ? loginForm.value.username : username
  loginForm.value.password = isNullOrUndefined(password) ? loginForm.value.password : decrypt(password)
  loginForm.value.rememberMe = isNullOrUndefined(rememberMe) ? false : Boolean(rememberMe)
}

getCode();
getCookie();

function queryUsernames(queryString, cb) {
  let usernames = localStorage.getItem('usernames');
  if (!usernames) {
    cb([])
    return
  }
  let arr = usernames.split(',').map(item => ({value: item}))
  const results = queryString ? arr.filter(item => item.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0) : arr
  cb(results)
}
</script>

<style lang='scss' scoped>
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  background-image: url("../assets/images/login-background.jpg");
  background-size: cover;
}
.title {
  margin: 0 auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  padding: 25px 25px 5px 25px;
  .el-input {
    height: 40px;
    input {
      height: 40px;
    }
  }
  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 0;
  }
}
.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}
.login-code {
  width: 33%;
  height: 40px;
  float: right;
  img {
    cursor: pointer;
    vertical-align: middle;
  }
}
.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial,serif;
  font-size: 12px;
  letter-spacing: 1px;
}
.login-code-img {
  height: 40px;
  padding-left: 12px;
}
</style>
